package com.zy.explore.sys.interfaces.assembler;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.zy.explore.common.infrastructure.util.DataBeanUtil;
import com.zy.explore.common.infrastructure.util.JwtUtil;
import com.zy.explore.common.interfaces.frm.CommonLongIdFrm;
import com.zy.explore.common.interfaces.vo.PageVO;
import com.zy.explore.sys.application.service.StationMsgService;
import com.zy.explore.sys.application.service.UserMsgService;
import com.zy.explore.sys.domain.mybatis.entity.StationMsg;
import com.zy.explore.sys.domain.mybatis.entity.UserMsg;
import com.zy.explore.sys.interfaces.frm.UserMsgFrm;
import com.zy.explore.sys.interfaces.vo.UserMsgVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户消息Assembler
 *
 * @author ChinaYin  主页:https://gitee.com/zy-explorej2ee 邮箱:zyexplorej2ee@sina.com
 * @date 2021年06月13日 12:13:50
 */
@Component
public class UserMsgAssembler {

    /**
     * 注入service
     */
    @Resource
    private UserMsgService service;

    @Resource
    private StationMsgService stationMsgService;

    /**
     * 新增数据
     *
     * @param frm 参数对象
     * @return 视图对象
     */
    public UserMsgVO insert(UserMsgFrm frm) {
        UserMsg entity = convertFromFrm(frm);
        entity.setCreateTime(new Date());
        UserMsg res = service.insertSelective(entity);
        if (res != null) {
            return convertToVO(res);
        }
        return null;
    }

    /**
     * 删除对象
     *
     * @param frm 参数对象
     * @return true:删除成功 false:删除失败
     */
    public Integer delete(CommonLongIdFrm frm) {
        return service.deleteByPrimaryKey(frm.getId());
    }

    /**
     * 更新对象
     *
     * @param frm 待更新的Frm对象
     * @return 成功返回更新后的VO对象，失败返回null
     */
    public UserMsgVO update(UserMsgFrm frm) {
        UserMsg entity = convertFromFrm(frm);
        entity.setUpdateTime(new Date());
        int res = service.updateByPrimaryKeySelective(entity);
        if (res == 1) {
            return convertToVO(entity);
        }
        return null;
    }

    /**
     * 根据ID查询数据
     *
     * @param frm 主键Frm对象
     * @return 成功返回对应ID的VO对象，失败返回null
     */
    public UserMsgVO findById(CommonLongIdFrm frm) {
        UserMsg entity = service.getByPrimaryKey(frm.getId());
        return convertToVO(entity);
    }

    /**
     * 根据条件查询数据集合
     *
     * @param frm 查询条件对象
     * @return 满足条件的数据集合
     */
    public List<UserMsgVO> getList(UserMsgFrm frm) {
        Example example = UserMsg.getExample(frm);
        List<UserMsg> list = service.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            List<UserMsgVO> retList = new ArrayList<>();
            list.forEach(x -> {
                UserMsgVO vo = convertToVO(x);
                fillParamsForVO(x, vo);
                retList.add(vo);
            });
            return retList;
        }
        return new ArrayList<>();
    }

    private void fillParamsForVO(UserMsg x, UserMsgVO vo) {
        StationMsg stationMsg = stationMsgService.getByPrimaryKey(x.getMsgId());
        vo.setMsgContent(stationMsg.getMsgContent());
        vo.setTitle(stationMsg.getTitle());
        vo.setPriority(stationMsg.getPriority());
        vo.setMsgType(stationMsg.getMsgType());
        String sendUsers = stationMsg.getSendUsers();
        if (StringUtils.isEmpty(sendUsers)) {
            vo.setUsers(Lists.newArrayList());
        } else {
            vo.setUsers(JSON.parseObject(sendUsers, List.class));
        }
    }

    /**
     * 根据条件查询分页
     *
     * @param frm 查询条件
     * @return 满足条件的分页
     */
    public PageVO<UserMsgVO> getPageInfo(UserMsgFrm frm) {
        Example example = UserMsg.getExample(frm);
        PageInfo<UserMsg> pageInfo = PageHelper.startPage(frm.getPageNum(), frm.getPageSize()).doSelectPageInfo(() -> service.selectByExample(example));
        PageRequest pageRequest = PageRequest.of(frm.getPageNum() - 1, frm.getPageSize());
        Page<UserMsgVO> retPage = new PageImpl<>(new ArrayList<>(), pageRequest, 0);
        if (pageInfo == null || CollectionUtils.isEmpty(pageInfo.getList())) {
            return new PageVO<>(retPage);
        }
        List<UserMsgVO> retList = new ArrayList<>();
        pageInfo.getList().forEach(x -> {
            UserMsgVO vo = convertToVO(x);
            fillParamsForVO(x, vo);
            retList.add(vo);
        });
        retPage = new PageImpl<>(retList, pageRequest, pageInfo.getTotal());
        return new PageVO<>(retPage);
    }

    /**
     * 查询用户发送的站内信
     *
     * @param frm 请求参数
     * @return {@link PageVO<UserMsgVO>}
     */
    public PageVO<UserMsgVO> getSendMsgPageInfo(UserMsgFrm frm) {
        if (frm.getPageNum() == null || frm.getPageNum() <= 0) {
            frm.setPageNum(1);
        }
        if (frm.getPageSize() == null || frm.getPageSize() <= 0) {
            frm.setPageSize(10);
        }
        Integer currentUserId = JwtUtil.getCurrentUserId();
        long total = stationMsgService.getSendMsgTotal(currentUserId);
        List<StationMsg> list = stationMsgService.getSendMsgList(currentUserId, frm.getPageNum(), frm.getPageSize());
        PageRequest pageRequest = PageRequest.of(frm.getPageNum() - 1, frm.getPageSize());
        Page<UserMsgVO> retPage = new PageImpl<>(new ArrayList<>(), pageRequest, 0);
        if (CollectionUtils.isEmpty(list)) {
            return new PageVO<>(retPage);
        }
        List<UserMsgVO> retList = new ArrayList<>();
        list.forEach(x -> {
            UserMsgVO vo = DataBeanUtil.copyOf(x, UserMsgVO.class, true);
            vo.setMsgId(x.getId());
            fillParamsForVO(UserMsg.builder().msgId(x.getId()).build(), vo);
            retList.add(vo);
        });
        retPage = new PageImpl<>(retList, pageRequest, total);
        return new PageVO<>(retPage);
    }

    /**
     * 逻辑删除对象
     *
     * @param dto 参数对象
     * @return 1:删除成功 其他:删除失败
     */
    public Integer logicDelete(CommonLongIdFrm dto) {
        service.updateByPrimaryKeySelective(UserMsg.builder().id(dto.getId()).delFlag(1).build());
        return 1;
    }

    /**
     * 获取用户未读的消息数量
     *
     * @param frm 查询参数对象
     * @return 返回未读消息数量
     */
    public int getUnReadMsgNum(UserMsgFrm frm) {
        frm.setUserId(JwtUtil.getCurrentUserId());
        frm.setReadStatus(0);
        List<UserMsgVO> list = this.getList(frm);
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        return list.size();
    }

    /**
     * 标记所有的消息为已读
     *
     * @param frm 入参对象
     * @return 返回更新的数量
     */
    public int readAll(UserMsgFrm frm) {
        UserMsg userMsg = convertFromFrm(frm);
        userMsg.setUpdateTime(new Date());
        Example example = new Example(UserMsg.class);
        example.createCriteria().andEqualTo("userId", JwtUtil.getCurrentUserId());
        return service.updateByExampleSelective(userMsg, example);
    }

    /**
     * 逻辑删除全部站内信
     *
     * @return 返回删除的数量
     */
    public int logicDeleteAll() {
        UserMsg userMsg = UserMsg.builder().delFlag(1).updateTime(new Date()).build();
        Example example = new Example(UserMsg.class);
        example.createCriteria().andEqualTo("userId", JwtUtil.getCurrentUserId()).andEqualTo("readStatus", 1).andEqualTo("delFlag", 0);
        return service.updateByExampleSelective(userMsg, example);
    }

    /**
     * 物理删除全部站内信
     *
     * @return 返回删除的数量
     */
    public int deleteAll() {
        Example example = new Example(UserMsg.class);
        example.createCriteria().andEqualTo("userId", JwtUtil.getCurrentUserId()).andEqualTo("delFlag", 1);
        return service.deleteByExample(example);
    }

    /**
     * frm转实体类
     *
     * @param frm 参数对象
     * @return 转换后的实体类对象
     */
    public static UserMsg convertFromFrm(UserMsgFrm frm) {
        return DataBeanUtil.copyOf(frm, UserMsg.class, true);
    }

    /**
     * 实体类转VO
     *
     * @param entity 实体类
     * @return 转换后的对象
     */
    public static UserMsgVO convertToVO(UserMsg entity) {
       return entity == null ? null : DataBeanUtil.copyOf(entity, UserMsgVO.class, true);
    }
}
